<?php

namespace app\admin\middleware;

use app\service\jwt\JwtService;
use Closure;
use think\facade\Db;
use think\Request;
use Throwable;


class AdminSessionMiddleware
{

    /**
     * @param Request $request
     * @param Closure $next
     * @return $this|mixed
     */
    public function handle(Request $request, Closure $next)
    {

        try {
            if(session('admin_id') && session('account') && session('admin_info')){
                $getRoutName = Request()->rule()->getName();
                //权限判断
                if($getRoutName == 'homeIndex' || $getRoutName == 'notPower'){
                    return $next($request);
                }else{
                    $getAdminPower = cache('adminPowerIdList'.session('admin_id'));
                    if($getAdminPower['role'] == 'all'){
                        return $next($request);
                    }else{
                        $getMenuInfo = Db::name('system_menu')->where('route_name',$getRoutName)->find();
                        if($getMenuInfo){
                            //有权限
                            if(in_array($getMenuInfo['menu_id'],$getAdminPower['roleIdList'])){
                                return $next($request);
                            //没有权限
                            }else{
                                if($getMenuInfo['params'] == 'get'){
                                    return redirect('/admin/notPower');
                                }else{
                                    return json()->data( [
                                        'message'=>'没有对应权限',
                                        'code'=>1,
                                        'data'=>[],
                                        'status'=>400,
                                        'msg'=>'没有对应权限',
                                    ]);
                                }
                            }
                        }else{
                            return redirect('/admin/notPower');
                        }
                    }
                }
            }else{
                return redirect('/admin/login/login');
            }
        } catch (Throwable $e) {
            return redirect('/admin/login/login');
        }
    }

}